﻿using Reporting.Errorcode;
using Reporting.API.Application.Commands.SaleOrders;
using MediatR;
using Reporting.API.Utils;
using Reporting.Domain;
using Reporting.Infrastructure.Interfaces.SaleOrders;
using AutoMapper;
using Reporting.Errorcode.ErrorCode;

namespace Reporting.API.Application.CommandHandler.SaleOrders
{
    /// <summary>
    /// 显示 销售订单
    /// </summary>
    public class GetSaleOrderCommandHandler : IRequestHandler<GetSaleOrderCommand, ApiResult<PagingResult<IList<SaleOrder>>>>
    {
        private readonly ISaleOrderRepository _saleOrderRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetSaleOrderCommandHandler> _logger;

        public GetSaleOrderCommandHandler(ILogger<GetSaleOrderCommandHandler> logger, IMapper mapper, ISaleOrderRepository saleOrderRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _saleOrderRepository = saleOrderRepository;
        }

        public async Task<ApiResult<PagingResult<IList<SaleOrder>>>> Handle(GetSaleOrderCommand request, CancellationToken cancellationToken)
        {
            // 获取所有生产计划
            var productionPlans = await _saleOrderRepository.GetAllAsync();


            // 当前页的数据
            var currentData = _mapper.Map<IList<SaleOrder>>(productionPlans.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize).ToList());

            // 分页
            var pagingResult = new PagingResult<IList<SaleOrder>>
            {
                TotalCount = productionPlans.Count(),
                TotalPage = Math.Ceiling(productionPlans.Count() / (double)request.PageSize),
                Data = currentData
            };

            // 返回成功结果
            return ApiResult<PagingResult<IList<SaleOrder>>>.Success(pagingResult, StatusCodeEnum.Success);
        }
    }
}
